package com.xteam.xnetworkdisk.utils;

import com.xteam.xnetworkdisk.constant.Constant;
import com.xteam.xnetworkdisk.utilsinterface.ChunkFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Component
public class ChunkFileRedisUtils implements ChunkFileUtils {

    @Autowired
    private RedisUtils redisUtils;

    public void write(String key, OutputStream thumbnailStream) {
        byte[] byteArray = ((ByteArrayOutputStream) thumbnailStream).toByteArray();
        String s = Base64Utils.encodeToBase64(byteArray);
        redisUtils.write(key,s);
    }

    public void write(String key, MultipartFile file) throws IOException {
        System.out.println("分片存入redis");
        byte[] fileBytes = file.getBytes(); // 获取文件的字节数组
        System.out.println("转码前分片大小："+ fileBytes.length);
        String s = Base64Utils.encodeToBase64(fileBytes);
        System.out.println("转码后分片大小"+ s.length());
        redisUtils.write(key,s);
    }

    // 读操作（主节点）
    public byte[] read(String key) {
        String chunkData = (String)redisUtils.readTemplate(key); // 从Redis中读取分片数据
        System.out.println("转码前"+ chunkData.length());
        byte[] bytes = Base64Utils.decodeFromBase64(chunkData);
        System.out.println("转码后"+ bytes.length);
        return bytes;
    }

    /**
     * 清理 Redis 中与文件上传相关的缓存。
     *
     * @param md5Value 文件的 MD5 值
     * @param chunks 分片总数
     */
    public void clearFileUploadCache(String md5Value, int chunks) {
        // 清理与分片相关的缓存
        for (int i = 1; i <= chunks; i++) {
            redisUtils.delete("file:upload:" + md5Value + ":" + i);
        }

        String videoThumbnail = "file:upload:" + md5Value + ":" + Constant.VIDEO_THUMBNAIL;
        redisUtils.delete(videoThumbnail);
    }

}
